<template>
  <el-dialog
    append-to-body
    :title="title"
    :width="width"
    :visible.sync="maindialogVisible"
    :close-on-click-modal="false"
    @close="close"
  >
    <el-form :model="temp" label-position="left" label-width="120px">
      <el-form-item label="state value">
        <el-input v-model="temp.state_value" type="number" />
      </el-form-item>
      <el-form-item label="website type">
        <el-select v-model="temp.website_type" placeholder="网站类型">
          <el-option label="WooCommerce" value="WooCommerce" />
          <el-option label="PrestaShop" value="PrestaShop" />
          <el-option label="BigCommerce" value="BigCommerce" />
          <el-option label="Shopify" value="Shopify" />
        </el-select>
      </el-form-item>
      <el-form-item label="关联网站">
        <el-input v-model="temp.domain" />
      </el-form-item>
      <el-form-item label="选择模板">
        <el-select v-model="temp.emailtemplate_id" placeholder="选择模板">
          <el-option v-for="item in this.templates" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
    </el-form>
    <el-alert
      v-if="hasGmailTips !==''"
      :title="hasGmailTips"
      type="warning"
    />
    <span slot="footer" class="dialog-footer">
      <el-button @click="maindialogVisible = false">取 消</el-button>
      <el-button :type="action !== 'delete'?'primary':'danger'" @click="confirm">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { Get, Post, Put, Delete } from '@/api/eco/emailtemplatewebstiestatebind'
import qs from 'qs'
import { Get as GetEmailTemplate } from '@/api/eco/emailtemplate'
import { Get as GetWebsite } from '@/api/erp/elicink/website'
import { GetGmailByDomain } from '@/api/orders/googlegmailaccount'

const orderMapper = {
  'ascending': 0,
  'descending': 1,
  'null': ''
}
export default {
  name: 'Newemailbind',
  props: ['website_domain', 'state_value', 'website_type', 'dialogVisible'],
  data() {
    return {
      title: '绑定邮件模板自动发送邮件',
      temp: {
        emailtemplate_id: '',
        state_value: '',
        website_type: 'PrestaShop',
        domain: ''
      },
      action: 'create',
      width: '60%',
      templates: [],
      maindialogVisible: false,
      website_options: [],
      remoteSearchWebsite_loading: false,
      hasGmailTips: ''
    }
  },
  watch: {
    dialogVisible(v) {
      this.maindialogVisible = v
      this.temp.domain = this.website_domain
      this.temp.state_value = this.state_value
      this.temp.website_type = this.website_type
      this.hasGmailTips = ''
      this.handleGetGmailAccount()
    }
  },
  created() {
    this.handleFetchtemplates()
  },
  methods: {
    handleGetGmailAccount() {
      GetGmailByDomain({ 'domain': this.temp.domain })
        .then(response => {
          if (response.data.total === 0) {
            this.hasGmailTips = '网站没有绑定gmail账号,邮件不会自动发送 请在 客服/gmail中进行设置'
            return
          }
          if (!response.data.data.sendable) {
            this.hasGmailTips = '网站绑定的gmail 账号' + response.data.data.gmail + '没有配置发送邮件功能， 请在 客服/gmail中进行设置'
          }
        }).catch(err => {
          console.table(err)
          this.hasGmailTips = '网站没有绑定gmail账号,邮件不会自动发送， 请在 客服/gmail中进行设置'
        })
    },
    setWebsiteOptions(v) {
      v.forEach(website => {
        GetWebsite(website).then(response => {
          this.website_options.push(response.data)
        })
      })
    },
    remoteSearchWebsite(query) {
      if (query !== '') {
        this.remoteSearchWebsite_loading = true
        GetWebsite(null, qs.stringify({
          kw: query,
          pagesize: 5,
          page: 1
        })).then(response => {
          this.website_options = response.data.data
          this.remoteSearchWebsite_loading = false
        })
      } else {
        this.website_options = []
        this.remoteSearchWebsite_loading = false
      }
    },
    resetTemp() {
      this.temp = {
        emailtemplate_id: '',
        state_value: '',
        website_type: 'PrestaShop',
        domain: ''
      }
    },
    getList() {
      this.listLoading = true
      Get(null, qs.stringify({
        kw: this.kwInput,
        pagesize: this.pagesize,
        page: this.page,
        order_by: this.order_by,
        order_desc: this.order_desc
      }))
        .then(response => {
          this.scrollTop()
          this.data = response.data.data
          this.listLoading = false
          this.total = response.data.total
        }).catch(err => {
          console.log(err)
          this.listLoading = false
        })
    },
    handleAction(action, row) {
      this.action = action
      switch (action) {
        case 'create':
          this.width = '50%'
          this.title = row
          this.resetTemp()
          this.maindialogVisible = true
          break
        case 'delete':
          this.width = '30%'
          this.title = `确认要删除${row.domain}?`
          this.temp = Object.assign({}, row)
          this.maindialogVisible = true
          break
        case 'edit':
          this.width = '50%'
          this.title = `修改站点${row.domain}`
          this.temp = Object.assign({}, row)
          this.maindialogVisible = true
          break
      }
    },
    confirm() {
      const _data = this.temp
      switch (this.action) {
        case 'create':
          if (!_data.website_type.length) {
            alert('website type必须填写')
            return
          }
          Post(_data
          ).then(response => {
            this.maindialogVisible = false
            this.getList()
            this.$emit('reload')
            this.notify('添加成功')
          })
          break
        case
          'delete'
          :
          Delete(_data.id).then((response) => {
            this.maindialogVisible = false
            this.getList()
            this.$emit('reload')
            this.notify('删除成功')
          })
          break
        case
          'edit'
          :
          Put(_data.id, _data).then((response) => {
            this.maindialogVisible = false
            this.$emit('reload')
            this.getList()
            this.notify('更新成功')
          })
          break
      }
    },
    notify(message, duration) {
      this.$notify({
        title: '成功',
        message: message,
        type: 'success',
        duration: duration || 2000
      })
    },
    // pageSize 改变后触发 table 更新
    handleSizeChange(val) {
      this.pagesize = val
      this.getList()
    },
    // page 改变后触发 table 更新
    handlePageChange(val) {
      this.page = val
      this.getList()
    },
    // 点击搜索
    handleSearch() {
      this.page = 1
      this.getList()
    },
    handleSort(v) {
      this.order_by = v.prop
      this.order_desc = orderMapper[v.order]
      this.getList()
    },
    scrollTop() {
      window.scrollTo(0, 0)
    },
    close() {
      console.log('close newmailbind dialog')
      this.$emit('closeMyDialog', false)
    },
    handleFetchtemplates() {
      GetEmailTemplate()
        .then(response => {
          this.templates = response.data.data
        })
        .catch(e => {
          console.log('error')
        })
    }
  }
}
</script>

<style scoped>

</style>
